<template>
    <div class="layout-container">
        <div class="layout-container-form  flex space-between">
            <div class="layout-container-form-handle">
                <el-upload ref="uploader" action="/api/accountManagement/importStudentsFromExcel" :auto-upload="true"
                    :data="uploader" accept=".xls, .xlsx" :show-file-list="false"
                    :on-success="handleStuExcelFileSuccess">
                    <el-button type="primary" style="margin-left: 10px">
                        <span>批量导入学生账号</span>
                    </el-button>
                </el-upload>
                <el-button type="primary" :icon="Download" class="export-excel-btn" @click="handleExportExcel">{{
                    $t('message.common.exportExcel') }}</el-button>
            </div>
        </div>
        <div class="layout-container-table">

            <Table ref="table" v-model:page="page" v-loading="loading" :showSelection="true" :data="tableData"
                style="min-height: 400px;" @getTableData="getTableData" id="printContent">
                <el-table-column label="Id" align="center" min-width="60px">
                    <template v-slot="{ row, $index }">
                        {{ calculateId($index) }}
                    </template>
                </el-table-column>

                <!-- 动态列 -->
                <el-table-column v-for="task in tableHeader" :key="task.id" :prop="task.prop" :label="task.label"
                    :align="task.align" :min-width="task.minWidth">
                    <template v-slot="{ row }">
                        {{ row[task.prop] }}
                    </template>
                </el-table-column>
            </Table>

        </div>

        <Layer :layer="layer" @getTableData="getTableData" v-if="layer.show" />

    </div>
</template>

<script lang="ts" setup>
import { ref, unref, reactive, onMounted } from "vue";
import { Page } from "@/components/table/type";
import { ElMessage } from "element-plus";
import { getCourseStudentsApi } from "@/api/course";
import { LayerInterface } from "@/components/layer/index.vue";
import Table from "@/components/table/index.vue";
import Layer from "./layer.vue";
import { Download } from '@element-plus/icons'
import { useStore } from 'vuex'
import { useI18n } from 'vue-i18n'
import { aoaToSheetXlsx } from '@/utils/exportExcel/ExportExcel'
onMounted(() => {
    getTableData(true)
})
const props = defineProps({
    course_id: {
        type: Number,
        required: true
    }
})
const store = useStore()
const uploader: Record<string, any> = {
   user_id: store.state.user.user_id,
   course_id: props.course_id,
};
const query = reactive({
    input: "",
});
const tableHeader = ref([])

// 弹窗控制器
const layer: LayerInterface = reactive({
    show: false,
    title: "新增",
    showButton: true,
});
// 分页参数, 供table使用
const page: Page = reactive({
    index: 1,
    size: 20,
    total: 0,
});

const loading = ref(true);
const tableData = ref([]); // 表格数据
const getTableData = (init: Boolean) => {
    loading.value = true
    if (init) {
        page.index = 1
    }
    let params = {
        page: page.index,
        pageSize: page.size,
        course_id: props.course_id,
        user_id: store.state.user.user_id,
        is_teacher: store.state.user.is_teacher,
        ...query
    }



    getCourseStudentsApi(params).then((res: any) => {
        if (res.code === 200) {
            let data = res.data.data;
            page.total = res.data.total_size;
            let title = res.data.title;
            while (tableHeader.value.length > 0) {
                tableHeader.value.pop();
            }
            title.forEach((item: any) => {
                tableHeader.value.push({ prop: item[0], label: item[1], align: 'center' })
            })
            data.forEach((d: any) => {
                d.loading = false;
            });
            tableData.value = data;
        }
        else {
            console.error(res.message)
        }
    }).catch((error) => {
        console.error('发生错误:', error);
        tableData.value = [];
        page.index = 1;
        page.total = 0;
    }).finally(() => {
        loading.value = false;
    });
}
const handleStuExcelFileSuccess = (response: any) => {
    ElMessage.success('上传成功')
}
// 导出Excel表格
const handleExportExcel = () => {

    let table = unref(tableData)
    let header = reactive([])
    for (let i = 0; i < tableHeader.value.length; i++) {
        header.push(tableHeader.value[i].label)
    }
    // data 值为tableHeader的prop值
    let data = reactive([])
    for (let i = 0; i < table.length; i++) {
        let row = []
        for (let j = 0; j < tableHeader.value.length; j++) {
            row.push(table[i][tableHeader.value[j].prop])
        }
        data.push(row)
    }

    aoaToSheetXlsx({
        data,
        header,
    })
}
const calculateId = (index: number) => {
    return (page.index - 1) * page.size + index + 1;
};
const { t } = useI18n()
</script>

<style lang="scss" scoped>
.statusName {
    margin-right: 10px;
}
</style>